﻿using King.Box.Cache;
using King.Box.Utils.Global;
using King.Box.Utils.Utils;
using System;
using System.Collections.Generic;
using King.Box.AdminWeb.Utils;

namespace King.Box.AdminWeb.Logic
{
    public class AuthorizationCustomerService
    {
        private static BasicService _basicService = new BasicService();
        private static string _encryKey = string.Empty;

        private static string encryKey
        {
            get
            {
                if (string.IsNullOrEmpty(_encryKey))
                    _encryKey = _basicService.GetDictionaryVal(GlobalConst.Dictionary_Cookie_SecureKey);

                return _encryKey;
            }
        }

        public static bool IsLogin
        {
            get
            {
                return UserId.HasValue;
            }
        }

        public static int? UserId
        {
            get
            {
                var token = CookieUtil.GetCookie(GlobalConst.Cookie_User);
                if (string.IsNullOrEmpty(token))
                    return null;

                string decryStr = string.Empty;
                try
                {
                    decryStr = DesUtil.Decrypt(token, encryKey);
                }
                catch (Exception ex)
                {
                    CookieUtil.ClearCookie(GlobalConst.Cookie_User);
                    throw ex;
                }

                int uid;
                int.TryParse(decryStr, out uid);
                return uid;
            }

            set
            {
                var token = DesUtil.Encrypt(value.ToString(), encryKey);

                CookieUtil.SetCookie(GlobalConst.Cookie_User, token);
            }
        }
    }

    public class AuthorizationApiService
    {
        public static string Token
        {
            get
            {
                return TokenCacheService.GetToken();
            }
        }

        public static Dictionary<string, string> AuthorizationHeader
        {
            get
            {
                return new Dictionary<string, string>()
                {
                    { "Authorization",string.Format("Bearer {0}",Token) }
                };
            }
        }
    }
}